<?php

namespace catchAdmin\storehouse\model;

use catchAdmin\stock\model\Stock;
use catchAdmin\storehouse\model\search\WarehousingSearch;
use catcher\base\CatchModel;
use catcher\CatchAuth;
use think\facade\Db;
use think\facade\Log;

/**
 *
 * @property int $id
 * @property string $warehousing_id
 * @property string $project_id
 * @property string $project_client
 * @property int $goods_number
 * @property string $customer_order_type
 * @property string $settlement
 * @property string $group_number
 * @property string $customer_business_number
 * @property string $relation_order
 * @property string $postposition_order
 * @property string $odd_numbers_one
 * @property string $odd_numbers_two
 * @property string $odd_numbers_three
 * @property string $entry_method
 * @property int $createtime
 * @property int $updatetime
 * @property int $deletetime
 * @property int $isstatus
 * @property int $sort
 * @property string $status
 * @property string $remarks
 * @property int $actual_number
 * @property int $admin_id
 */
class Warehousing extends CatchModel
{
    use WarehousingSearch;
    public $field = [
        // ID
        'id',
        // 入库编号
        'warehousing_id',
        // 项目id(关联项目表)
        'project_id',
        // 委托方ID(关联项目的下级分类表)
        'project_client',
        // 商品总数量
        'goods_number',
        // 入库客户订单类型
        'customer_order_type',
        // 结算方
        'settlement',
        // 订单组号
        'group_number',
        // 客户业务单号
        'customer_business_number',
        // 关联订单号
        'relation_order',
        // 后置作业单号
        'postposition_order',
        // 参考单号1
        'odd_numbers_one',
        // 参考单号2
        'odd_numbers_two',
        // 参考单号3
        'odd_numbers_three',
        // 录入方式
        'entry_method',
        // 创建时间
        'created_at',
        // 更新时间
        'updated_at',
        // 删除时间
        'deleted_at',
        // 入库状态:0=未入库,1=全部入库,2=部分入库
        'status',
        // 备注
        'remarks',
        // 实际入库数量
        'actual_number',
        //创建人ID
        'creator_id',
        //商户ID
        'tenant_id',
        'take_date',
        'take_code',
        'new_customer_name',//客户名称
        'new_order_date',//订单日期
        'new_goods_description',//货物品名描述
        'new_entry_certificate_number',//入库凭证号
        'Original',//Original
        'Destination',//Destination
        'new_order_status',//货物状态
        'new_tray_num',//货物托盘数量
        'new_box_num',//货物箱数
        'new_gross_weight',//货物毛重
        'new_goods_dimension',//货物尺寸
        'new_goods_price',//货物金额
        'shipper_serial_number',//托运人 代码 C0001
        'shipper_relation_name',//联系人
        'shipper_relation_phone',//联系方式
        'shipper_addr',//联系地址
        'consignee_serial_number',//收货人 代码 C0002
        'consignee_relation_name',//联系人
        'consignee_relation_phone',//联系方式
        'consignee_addr',//地址
        'delivery_config_id',//收货地-库名ID
        'delivery_addr',//库名地址
        'delivery_config_name',//库名
        'transport_type',//运输方式
        'waybill',//运单号
        'clause',//条款
        'delivery_relation_name',
        'delivery_relation_phone',
        'warehousing_config_attribute',
        'edi_json',
        'edi_return',
        'batch_no'
    ];
    
    public $name = 'db_warehousing';
    /**
   * 列表
   * @throws \think\db\exception\DbException
//   * @return \think\Paginator
   */
    public function getList($tenant_id = 0,$project_name='',$id = 0,$position=0,$type=0)
    {
        $user = (new CatchAuth())->user();
        $user_id = $user->id;
        $where = [];
        if($tenant_id !== 0){
            $where[]=['w.tenant_id','=',$tenant_id];

            if($type==3){//员工账号，拿到所有项目
                $projectIds = (new Project)->where([
                    ['pid','>',0],
                    ['tenant_id','=',$tenant_id],
                    ['employees','find in set', $user_id],
                ])->column('project_id');
                $where[] = ['w.project_client','in',$projectIds];
            }

//            if($type==3 && $position!=1){
//                $where[]=['w.creator_id','=',$id];
//            }
        }
        if($project_name){
            $where[]=['p.project_name','like',"%$project_name%"];
        }

        return $this->catchSearch()
                    ->alias('w')
                    ->leftJoin('db_project p','w.project_id = p.project_id')
                    ->leftJoin('db_project pr','w.project_client = pr.project_id')
                    ->order('w.id','desc')
                    ->field(['w.warehousing_config_attribute,w.take_code,w.take_date,w.creator_id,w.id,w.warehousing_id,w.goods_number,w.customer_order_type,w.settlement,w.group_number,w.customer_business_number,w.relation_order,w.postposition_order,w.odd_numbers_one,w.odd_numbers_two,w.odd_numbers_three,w.entry_method,w.created_at,w.status,w.remarks,w.actual_number,w.project_client,p.project_name,pr.project_name as project_name_two',
                        'w.new_order_status','w.new_order_date',
                        'w.*'
                    ])
                    ->where($where)
                    ->paginate()
                    ->each(function (&$item){
                        $item['new_order_date'] = date("Y-m-d",strtotime($item['new_order_date']));
                        $item['pub_name'] = Db::table('users')
                            ->where([['deleted_at','=',0],['id','=',$item['creator_id']]])
                            ->value('username');

                        $warehousing_config_attribute = explode(',',$item['warehousing_config_attribute']);
                        $config_parent_id = (int)Db::table('db_warehouse_config')->where('id',$warehousing_config_attribute[1])->value('parent_id');
                        $item['checked_config'] = ['_' . $warehousing_config_attribute[0], $config_parent_id,(int)$warehousing_config_attribute[1]];
                        $item['checked_config_status'] =  $warehousing_config_attribute[0];
                    });
    }


//    public static function onBeforeInsert($warehousing)
//    {
//        $warehousing_count = Db::table('db_warehousing')->where('tenant_id',$warehousing->tenant_id)->whereMonth('created_at')->count();
//        $warehouse_out_count = Db::table('db_warehouse_out')->where('tenant_id',$warehousing->tenant_id)->whereMonth('created_at')->count();
//        $new_id = $warehousing_count + $warehouse_out_count;
//
//        $co_code = Db::table('users')->where('id',$warehousing->tenant_id)->value('co_code');
//        if($co_code){
//            $head = strtoupper($co_code) . "IB";
//        }else{
//            $head = "CIWUXCN" . "IB";
//        }
//
//        $yearMonth = date("ym");
//        if (!empty($warehousing->remarks) && preg_match('/^\d{10}$/', $warehousing->remarks)) {
//            $yearMonth = date("ym",$warehousing->remarks);
//        }
//
//        $warehousing->warehousing_id =  $head . $yearMonth . str_pad($new_id + 1,5,'0',STR_PAD_LEFT);
//    }

    public static function onAfterInsert($warehousing)
    {
        $warehousing_count = Db::table('db_warehousing')->where('tenant_id',$warehousing->tenant_id)->whereMonth('created_at')->count();
        $warehouse_out_count = Db::table('db_warehouse_out')->where('tenant_id',$warehousing->tenant_id)->whereMonth('created_at')->count();
        $new_id = $warehousing_count + $warehouse_out_count;

        $co_code = Db::table('users')->where('id',$warehousing->tenant_id)->value('co_code');
        if($co_code){
            $head = strtoupper($co_code) . "IB";
        }else{
            $head = "CIWUXCN" . "IB";
        }

        $yearMonth = date("ym");
        if (!empty($warehousing->remarks) && preg_match('/^\d{10}$/', $warehousing->remarks)) {
            $yearMonth = date("ym",$warehousing->remarks);
        }

        if($warehousing->tenant_id == '10148'){
            $warehousing->warehousing_id =  $head . $yearMonth . str_pad($new_id,5,'0',STR_PAD_LEFT);
        }else{
            $warehousing->warehousing_id =  $head . $yearMonth . str_pad($new_id + 1,5,'0',STR_PAD_LEFT);
        }

        $warehousing->save();
    }

    public function todayNumber(){
        $user = (new CatchAuth)->user();

        $where = [
            ['deleted_at','=',0],
        ];

        if($user['type'] !== 1) {//普通商户
            $where[] = ['tenant_id','=',$user['tenant_id']];
        }

        $warehousing = $this->where($where)->whereDay('created_at')->field('IFNULL(SUM(goods_number),0) as total_number,IFNULL(SUM(actual_number),0) as already_number')->find();

        return $warehousing;
    }
}